package com.example.controller;

import com.example.dao.TrainingCycleCrudRepository;
import com.example.dao.TrainingPlanCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.TrainingCycle;
import com.example.pojo.TrainingPlan;
import com.example.pojo.PageBean;
import com.example.pojo.User;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/trainingPlan")
@Slf4j
public class TrainingPlanController {
    @Autowired
    private TrainingPlanCrudRepository trainingPlanCrudRepository;
    @Autowired
    private TrainingCycleCrudRepository trainingCycleCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;

    @PostMapping("/addTrainingPlan")
    public Result add(@RequestBody TrainingPlan trainingPlan) {
        //设置结束日期
        TrainingCycle trainingCycleById = trainingCycleCrudRepository.getTrainingCycleById(trainingPlan.getCycleId());
        Integer day = trainingCycleById.getCycle();
        trainingPlan.setEndTime(trainingPlan.getBeginTime().plusDays(day));
        TrainingPlan save = trainingPlanCrudRepository.save(trainingPlan);
        return Result.success(save);
    }

    @DeleteMapping("/deleteTrainingPlan")
    public Result delete(@RequestBody List<Integer> ids) {

        for (Integer id : ids) {
            trainingPlanCrudRepository.deleteById(id);
        }
        return Result.success("删除成功");
    }

    @PostMapping("/updateTrainingPlan")
    public Result update(@RequestBody TrainingPlan trainingPlan) {
        TrainingCycle trainingCycleById = trainingCycleCrudRepository.getTrainingCycleById(trainingPlan.getCycleId());
        Integer day = trainingCycleById.getCycle();
        trainingPlan.setEndTime(trainingPlan.getBeginTime().plusDays(day));
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(trainingPlan.getEndTime())) {
            trainingPlan.setStatus("已过期");
        }
        TrainingPlan save = trainingPlanCrudRepository.save(trainingPlan);
        return Result.success(save);
    }

    @PostMapping("/getAllTrainingPlan")
    public Result getAllTrainingPlan(@RequestBody TrainingPlan trainingPlan,
                                     @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                     @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        System.out.println(trainingPlan);
        log.info("TrainingPlan:{}", trainingPlan);
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.Direction.ASC, "id");

        Page<TrainingPlan> coursePage = trainingPlanCrudRepository.findAll(new Specification<TrainingPlan>() {
            @Override
            public Predicate toPredicate(Root<TrainingPlan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (trainingPlan != null) {
                    //根据 student 的属性添加查询条件
                    if (trainingPlan.getId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("id"), trainingPlan.getId()));
                    }
                    if(user.getRole().equals("学员")){
                        predicate.getExpressions().add(cb.isNotNull(root.get("status")));
                    }
                    if (trainingPlan.getName() != null && !trainingPlan.getName().isEmpty()) {
                        // 模糊搜索 name 字段
                        predicate.getExpressions().add(cb.like(root.get("name"), "%" + trainingPlan.getName() + "%"));
                    }
                }
                return predicate;
            }
        }, pageable);
        List<TrainingPlan> TrainingPlans = coursePage.getContent();
        long elements = coursePage.getTotalElements();
        return Result.success(new PageBean(elements, TrainingPlans));
    }

    @GetMapping("/getTrainingPlanList")
    public Result getTrainingPlanList() {
        Iterable<TrainingPlan> all = trainingPlanCrudRepository.findAll();
        List<TrainingPlan> trainingPlanList = new ArrayList<>();
        for (TrainingPlan trainingPlan : all) {
            trainingPlanList.add(trainingPlan);
        }
        return Result.success(trainingPlanList);
    }

}
